<template>
  <div class="table-data">
    <el-form
      :rules="rules"
      ref="ruleForm"
      :model="form"
      size="small"
      class="form-box"
    >
    
    <!-- <p class="title">基础信息设置</p> -->
    <el-tabs type="border-card">
      <el-tab-pane label="基础信息">
        <el-form-item label="商品标题" prop="title">
          <el-input type="text" v-model="form.title" placeholder="请输入商品标题"></el-input>
        </el-form-item>
        <el-form-item label="商品副标题" prop="sub_title">
          <el-input type="text" v-model="form.sub_title" placeholder="请输入商品副标题"></el-input>
        </el-form-item>
        <el-form-item label="封面图片" prop="cover">
          <uploadImg @bindSendImg="propImg" :imgUrl="form.cover"></uploadImg>
        </el-form-item>
        <el-form-item label="商品轮播图">
          <uploadImgList @bindSendImgList="propImgList" :imgUrl="form.images"></uploadImgList>
        </el-form-item>
        <el-form-item label="商品类型" prop="verify_type">
          <el-radio-group v-model="form.verify_type ">
            <!-- <el-radio :label="0">物流商品</el-radio>
            <el-radio :label="1">核销商品</el-radio> -->
            <el-radio :label="'ship'">物流商品</el-radio>
            <el-radio :label="'code'">核销商品</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="制码模式" prop="ticket_type">
          <el-radio-group v-model="form.ticket_type">
            <el-radio :label="1">自建商品</el-radio>
            <el-radio :label="2">导码商品</el-radio>
            <el-radio :label="3">制码商品</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="售卖时间">
          <el-date-picker
              v-model="saleDateTime"
              type="datetimerange"
              value-format="yyyy-MM-dd hh:mm:ss"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期">
            </el-date-picker>
        </el-form-item>
        <el-form-item label="是否可退" prop="refund_able">
          <el-radio-group v-model="form.refund_able">
            <el-radio :label="1">可以退</el-radio>
            <el-radio :label="0">不可退</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="上下架状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">上架</el-radio>
            <el-radio :label="2">下架</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="供应商">
          <el-select v-model="form.vendor_id" clearable placeholder="供应商">
            <el-option v-for="item in supplierList" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属商家">
          <el-select v-model="form.shop_id" clearable placeholder="所属商家">
            <el-option v-for="item in businessList" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品所属标签" prop="application">
          <el-select v-model="form.tag_ids" multiple placeholder="请选择">
            <el-option
            v-for="item in labelList"
            :key="item.id"
            :label="item.tag"
            :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品所属分类">
          <!-- <el-cascader
            :options="form.location"
            v-model="kindList"
            @change="handleChange">
          </el-cascader> -->
          <el-select v-model="form.cate_id" clearable placeholder="一级分类" @change="handleChange">
            <el-option v-for="item in kindList" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
          <el-select v-model="form.sub_cate_id" clearable placeholder="二级分类" @change="handleChangeTwo" style="margin:0 10px">
            <el-option v-for="item in kindListTwo" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
          <el-select v-model="form.third_sub_cate_id" clearable placeholder="三级分类">
            <el-option v-for="item in kindListThree" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
      </el-tab-pane>
      <!-- <el-tab-pane label="购买须知">
        <el-form-item label="" prop="application">
          <ueditor :content="form.content" :key="timer" @ueditor-change="editorChange"></ueditor>
        </el-form-item>
      </el-tab-pane> -->
      <el-tab-pane label="商品详情">
        <ueditor :content="form.describe" :key="timer" @ueditor-change="editorChange"></ueditor>
      </el-tab-pane>
      <el-tab-pane label="核销码">
        <el-form-item label="与商家结算时机" prop="verify_way">
          <el-select v-model="form.verify_way" clearable placeholder="请选择">
            <el-option label="核销后几天" value="1"></el-option>
            <el-option label="发货后几天" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="具体几天" prop="verify_day">
          <el-input type="number" min="0" v-model="form.verify_day"></el-input>
        </el-form-item>
        <el-form-item label="一个商品生成的核销数码数量（无关规格）" prop="create_ticket_num">
          <el-input type="number" min="1" v-model="form.create_ticket_num"></el-input>
        </el-form-item>
        <el-form-item label="核销码保护期" prop="verify_hour">
          <el-input type="text" v-model="form.verify_hour"></el-input>
        </el-form-item>
        <el-form-item label="核销码有效期">
          <el-date-picker
              v-model="dateTime"
              type="datetimerange"
              value-format="yyyy-MM-dd hh:mm:ss"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期">
            </el-date-picker>
        </el-form-item>
      </el-tab-pane>
      <el-tab-pane label="价格设置">
        <el-row>
          <el-col :span="24">
            <el-form-item label="商品规格" prop="guige">
              <el-radio-group v-model="guige">
                <el-radio :label="1">单规格</el-radio>
                <el-radio :label="2">多规格</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col v-if="guige==2">
            <el-form-item label="商品规格" prop="spec">
              <div class="specBox">
                <ul>
                  <li v-for="(specItem, i) in specItems" :key="i">
                    <el-input v-model="specItem.standardValue" style="width: 220px"  @blur.prevent="setParentInput(specItem.standardValue, i)" placeholder="请填写规格名称(如：颜色)"></el-input>
                    <el-input v-model="specItem.specName" style="width: 220px" placeholder="请填写规格值(如：红色)"></el-input>
                    <el-button type="primary" class="button" size="small" @click="addSpecVal(i)">添加</el-button>
                    <el-button type="danger" size="small" @click="delliEle(i)">删除</el-button>
                    <div>
                      <el-tag v-for="(item,index) in specItem.specNames" closable :disable-transitions="false" :key="item" @close="closeTag(i, index)">{{item}}</el-tag>
                    </div>
                  </li>
                </ul>
                <el-button type="primary" size="small" @click="add()">添加规格</el-button>
                <el-form>
                  <table class="specTable" v-if="show">
                    <thead>
                      <th v-for="(th,i) in arr" :key="i">{{th}}</th>
                      <th v-if="form.verify_type!='ship'">每个核销码商家结算价</th>
                      <th>商家结算价</th>
                      <th v-if="form.verify_type!='ship'">每个核销码默认渠道结算价</th>
                      <th>渠道商结算价</th>
                      <th>原价</th>
                      <th>建议售价</th>
                      <th>库存</th>
                      <!-- <th>操作</th> -->
                    </thead>
                    <tbody>
                      <tr v-for="(tr, index) in trs" :key="index">
                        <td v-for="(td,i) in tr" :key="i">{{td}}</td>
                        <td><el-input size="mini" v-model="trsVals[index].sell_price" type="number" min="1" @change="getSellPrice(trsVals[index].sell_price, index)"></el-input></td>
                        <td v-if="form.verify_type!='ship'">{{trsVals[index].supplierPrice}}</td>
                        <td v-if="form.verify_type!='ship'"><el-input size="mini" type="number" min="1" v-model="trsVals[index].channel_settle_price" @change="getchannelPrice(trsVals[index].channel_settle_price, index)"></el-input></td>
                        <td>{{trsVals[index].channelPrice}}</td>
                        <td><el-input size="mini" type="number" min="1" v-model="trsVals[index].original_price" @keyup.native="wnum" @change="getOriginalPrice(trsVals[index].original_price, index)"></el-input></td>
                        <td><el-input size="mini" type="number" min="1" v-model="trsVals[index].suggest_price" @change="getSuggestPrice(trsVals[index].suggest_price, index)"></el-input></td>
                        <td><el-input size="mini" type="number" min="1" v-model="trsVals[index].stock" @change="getStock(trsVals[index].stock, index)"></el-input></td>
                        <!-- <td>
                          <el-switch v-model="switchArr[index].isActive" active-color="#13ce66" inactive-color="#ff4949" active-text="启用" inactive-text="禁用" @change="switchChange($event,index)"></el-switch>
                        </td> -->
                      </tr>
                    </tbody>
                  </table>
                </el-form>
              </div>
            </el-form-item>
          </el-col>
          <el-col v-else>
            <el-col :span="24" v-if="form.verify_type=='ship'">
              <p class="price-title">价格设置自营物流产品</p>
              <el-form-item label="商家结算价" prop="merchant_settle_price">
                <el-input type="number" min="1" v-model="form.merchant_settle_price"></el-input>
              </el-form-item>
              <el-form-item label="渠道结算价" prop="channel_settle_price">
                <el-input type="number" min="1" v-model="form.channel_settle_price"></el-input>
              </el-form-item>
              <el-form-item label="原价" prop="original_price">
                <el-input type="number" min="1" v-model="form.original_price"></el-input>
              </el-form-item>
              <el-form-item label="建议零售价" prop="suggest_price">
                <el-input type="number" min="1" v-model="form.suggest_price"></el-input>
              </el-form-item>
              <el-form-item label="库存" prop="stock">
                <el-input type="number" min="1" v-model="form.stock"></el-input>
              </el-form-item>
              <el-form-item label="重量（单位g）" prop="weight">
                <el-input type="number" min="0" v-model="form.weight"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24" v-else>
              <el-form-item label="每个核销码供应商结算价" prop="vendor_settle_price">
                <el-input type="number" min="1" v-model="form.vendor_settle_price" @blur="getSupplierPrice()"></el-input>
              </el-form-item>
              <el-form-item label="单商品供应商算价">
                <span class="price-txt">{{supplierPrice}}</span>
                <span class="price-tip">每个核销码供应商结算价*单个商品生成码数量</span>
              </el-form-item>
              <el-form-item label="每个核销码默认渠道结算价" prop="channel_settle_price">
                <el-input type="number" min="1" v-model="form.channel_settle_price" @blur="getchannelPrices()"></el-input>
              </el-form-item>
              <el-form-item label="单商品渠道结算价">
                <span class="price-txt">{{channelPrice}}</span>
                <span class="price-tip">每个核销码默认渠道结算价*单个商品生成码数量</span>
              </el-form-item>
              <el-form-item label="原价" prop="original_price">
                <el-input type="number" min="1" v-model="form.original_price"></el-input>
              </el-form-item>
              <el-form-item label="建议售价（单个商品，非单个核销码）" prop="suggest_price">
                <el-input type="number" min="1" v-model="form.suggest_price"></el-input>
              </el-form-item>
              <el-form-item label="库存" prop="stock">
                <el-input type="number" min="1" v-model="form.stock"></el-input>
              </el-form-item>
              <el-form-item label="重量（单位g）" prop="weight">
                <el-input type="number" min="1" v-model="form.weight"></el-input>
              </el-form-item>
            </el-col>
          </el-col>
        </el-row>
      </el-tab-pane>
      <el-tab-pane label="物流设置" v-if="form.verify_type=='0'">
        <el-form-item label="物流信息" prop="title">
          <el-radio-group v-model="form.client">
            <el-row>
              <el-col :span="24" style="margin-bottom:18px">
                <el-radio :label="0">统一运费</el-radio>
                <el-input type="text" v-model="form.shipping_price"></el-input>
              </el-col>
              <el-col :span="24">
                <el-radio :label="1">运费模板</el-radio>
                <el-select v-model="form.stock" clearable placeholder="请选择">
                  <el-option label="美食" value="1"></el-option>
                  <el-option label="生活" value="2"></el-option>
                  <el-option label="出行" value="3"></el-option>
                  <el-option label="娱乐" value="4"></el-option>
                  <el-option label="旅游" value="5"></el-option>
                </el-select>
              </el-col>
            </el-row>
          </el-radio-group>
        </el-form-item>
      </el-tab-pane>
    </el-tabs>
    </el-form>
    <div class="dialog-footer">
      <el-button @click="cancel" size="small">取消</el-button>
      <el-button @click="submitFormAdd('ruleForm')" type="primary" size="small">确定</el-button>
    </div>
  </div>
</template>

<script lang="ts">
import { Component, Vue, Prop, Provide, Watch } from "vue-property-decorator";
import ueditor from "@/components/ueditor/index.vue";
import uploadImg from "@/components/uploadImg/index.vue";
import uploadImgList from "@/components/uploadImg/list.vue";
import goodsApi from "@/api/goods";
import businessApi from "@/api/business";
import supplierApi from "@/api/supplier";
@Component({
  components: {uploadImg,uploadImgList,ueditor}
})
export default class goodsAddDialog extends Vue {
  // 属性或参数中使用 ！：表示强制解析（告诉typescript编译器，这里一定有值），常用于vue-decorator中的@Prop
  @Provide() timer:any=''
  @Provide() dateTime: any = [];//核销时间
  @Provide() saleDateTime: any = [];//售卖时间
  @Provide() value1: any = [];
  @Provide() imgList: any=[];//轮播列表
  @Provide() labelList: any=[];//标签列表
  @Provide() supplierList: any=[];//供应商列表
  @Provide() businessList: any=[];//商家列表
  @Provide() advertiser: any = [];//广告商
  @Provide() kindList: any = [];//所属分类列表
  @Provide() kindListTwo: any = [];//所属分类列表
  @Provide() kindListThree: any = [];//所属分类列表
  @Provide() state: boolean = false; // 状态默认值
  @Provide() guige: any = 1; // 规格
  @Provide() supplierPrice: any = ""; // 供应商算价
  @Provide() channelPrice: any = ""; // 渠道结算价
  @Provide() searchMapS:{//供应商查询条件
    name: string,
    phone:string,
  }={
    name:'',
    phone:''
  }
  @Provide() searchMapB:{
    keyword: string,
    cate_id: string,
    is_child: any,
  }={
    keyword: "",
    cate_id: "",
    is_child: 0
  }
  @Provide() searchItem:{
    item: string,
    parent_id: string,
    goods_id: any,
  }={
    item: "",
    parent_id: "",
    goods_id: ""
  }
  @Provide() form:any={
    id:"",
    barcode:"",
    title:'',
    sub_title:'',
    cate_id:'',
    sub_cate_id:'',
    third_sub_cate_id:'',
    brand_id:'',
    stock:'',
    shipping_id:'',
    shipping_price:'',
    weight:'',
    cubage:'',
    status:'',
    price:'',
    cover:'',
    sale_on_time:'',
    sale_off_time:'',
    original_price:'',
    vendor_price:'',
    vendor_settle_price:'',
    channel_settle_price:'',
    merchant_settle_price:'',
    suggest_price:'',
    unit_name:'',
    vendor_id:'',
    shop_id:'',
    refund_able:'',
    ticket_type:'',
    verify_type:'',
    verify_way:'',
    verify_day:'',
    verify_start_time:'',
    verify_end_time:'',
    verify_hour:'',
    verify_ticket_num:'',
    create_ticket_num:'',
    describe:'',
    images:[
      // {
      //   url:'',
      //   order:'',
      //   is_main:''
      // }
    ],
    spec_item:[
      // {
      //   id:'',
      //   item:'',
      //   parent_id:''
      // }
    ],
    spec_goods_price:[
      // {
      // key:'',
      // key_name:'',
      // price:'',
      // vendor_price:'',
      // platform_price:'',
      // sell_price:'',
      // channel_settle_price:'',
      // suggest_price:'',
      // stock:'',
      // bar_code:'',
      // sku:'',
      // spec_img:'',
      // status:'',
      // original_price:'',
      // sale_stock:''
    // }
    ]

  };
  @Provide() rules: any = {
    title: [{ required: true, message: "请输入商品标题", trigger: "blur" }],
    stock: [{ required: true, message: "请输入库存", trigger: "blur" }],
    shipping_price: [{ required: true, message: "请输入运费价格", trigger: "blur" }],
    weight: [{ required: true, message: "请输入重量", trigger: "blur" }],
    price: [{ required: true, message: "请输入售价", trigger: "blur" }],
    original_price: [{ required: true, message: "请输入原价", trigger: "blur" }],
    channel_settle_price: [{ required: true, message: "请输入渠道结算价", trigger: "blur" }],
    merchant_settle_price: [{ required: true, message: "请输入商家结算价", trigger: "blur" }],
    suggest_price: [{ required: true, message: "请输入建议零售价", trigger: "blur" }],
    refund_able: [{ required: true, message: "请输选择是否可退", trigger: "change" }],
    status: [{ required: true, message: "请输选择上下架", trigger: "change" }],
    ticket_type: [{ required: true, message: "请选择制码模式", trigger: "change" }],
    verify_type: [{ required: true, message: "请选择商品类型", trigger: "change" }],
    verify_way: [{ required: true, message: "请选择与商家结算时机", trigger: "change" }],
    verify_day: [{ required: true, message: "请输入具体几天", trigger: "blur" }],
    verify_hour: [{ required: true, message: "请输入核销码保护期", trigger: "blur" }],
    describe: [{ required: true, message: "请输入商品详情描述", trigger: "blur" }],
    verify_ticket_num: [{ required: true, message: "请输入单个商品可使用次数", trigger: "blur" }],
    create_ticket_num: [{ required: true, message: "请输入单个商品生成核销码数量", trigger: "blur" }],
    // dateTime: [{ required: true, message: "请选择核销码有效期", trigger: "change" }],
    // saleDateTime: [{ required: true, message: "请选择售卖时间", trigger: "change" }],
  };
  @Provide() specItems:any= []  // 规格数组
  @Provide() spec:any= []  // 
  @Provide() trsVals:any= []  // 
  @Provide() show:boolean= false  // 
  @Provide() disable:boolean= false  // 
  @Provide() trs:any= []  //
  @Provide() arr:any= []  //
  @Provide() allSpec:any= []  //
  @Provide() addSpec:any= []  //

  @Provide() switchArr:any= []  //
  @Provide() result:any= []  //
  @Provide() seleIndex:any= []  //多规格选中输入框的下标（商家结算价）
  @Provide() seleVal:any= []  //多规格选中输入框的值（商家结算价）
  @Provide() channelIndex:any= []  //多规格选中输入框的下标（渠道结算价）
  @Provide() channelVal:any= []  //多规格选中输入框的值（渠道结算价）
  // 启用禁用
  handleDisable(i,row:any){
    if(i==1){
      this.form.spec_goods_price[i].status=1
    }else{
      this.form.spec_goods_price[i].status=0
    }
    // goodsApi.disabledAdmin(row.id,this.status)
    // .then((res: any) => {
    //   if(res.data.status){
    //     this.$message({
    //       message: '操作成功',
    //       type: "success"
    //     });
    //   }
      // this.loadData()spec_goods_price
    // });
  }
  // 监听商家结算价
  @Watch("form.vendor_settle_price")
  getSupplierPrice(){
    this.supplierPrice=this.form.vendor_settle_price*this.form.create_ticket_num
  }
  @Watch("form.channel_settle_price")
  getchannelPrices(){
    this.channelPrice=this.form.channel_settle_price*this.form.create_ticket_num
  }
  @Watch("form.create_ticket_num")
  getTicketNum(){
    this.supplierPrice=this.form.vendor_settle_price*this.form.create_ticket_num
    this.channelPrice=this.form.channel_settle_price*this.form.create_ticket_num
    this.trsVals.forEach(item=>{
      item.supplierPrice=item.sell_price*this.form.create_ticket_num
      item.channelPrice=item.channel_settle_price*this.form.create_ticket_num
    })
  }
  // 商家结算价
  getSellPrice(val, index) {
    if (Number(val) <= 0) {
      this.trsVals[index].price = null;
      // Message({
      //   type: 'error',
      //   message: '售价必须大于0'
      // });
      return;
    }
    this.result[index].platform_price = val;
    this.seleIndex=index
    this.seleVal=val
    this.form.spec_goods_price = this.result;
    console.log(this.seleIndex)
  }
  // @Watch(`form.spec_goods_price`)
  // getSellPrices(){
  //   console.log(1121)
  //   // this.result[this.seleIndex].supplierPrice = this.seleVal*this.form.create_ticket_num
  //   // // this.channelPrice=this.form.channel_settle_price*this.form.create_ticket_num
  // }
  // 原价
  getOriginalPrice (val, index) {
    if (Number(val) <= 0) {
        this.trsVals[index].original_price = null;
        // Message({
        //     type: 'error',
        //     message: '原价必须大于0'
        // });
        return;
    }
    this.result[index].original_price = val;
    this.form.spec_goods_price = this.result;
  }
  // // 建议零售价
  getSuggestPrice (val, index) {
      this.result[index].suggest_price = val;
      this.form.spec_goods_price = this.result;
  }
  // 渠道结算价
  getchannelPrice(val, index){
    this.channelIndex=index
    this.channelVal=val
    this.result[index].channel_settle_price = val;
    this.form.spec_goods_price = this.result;
    console.log(this.result)
  }
  // 库存
  getStock(val, index) {
    this.result[index].stock = val;
    this.form.spec_goods_price = this.result;
  }
  add() {
    this.specItems.push({
      id: '',
      specNames: [],
      specName: '',
      spec: this.spec,
      checkboxVals: [],
      checkboxes: []
    });
  }
  closeTag(i, index) {
    let len = this.trsVals.length;
    let len1 = this.specItems[i].specNames.length;
    let len2 = Math.floor(len / len1); 
    this.trsVals.splice(len2, len1);
    let delTag = this.specItems[i].specNames[index];
    let arr = this.trs.filter(item => {
      if (item.indexOf(delTag) === -1) {
        return item;
      }
    });
    this.trs = arr;
    this.specItems[i].specNames.splice(index, 1);
    this.form.spec_item[i].children.splice(index, 1);
    this.addSpec[i].children.splice(index, 1);
    // // 规格值数组为空，则删除当前规格
    if (!this.specItems[i].specNames.length) {
      this.delliEle(i);
    }
    this.creatTable()
  }
  delliEle(index) {
    this.specItems.splice(index, 1);
    this.addSpec.splice(index, 1);
    this.form.spec_item.splice(index, 1);
    if (this.specItems.length === 0) {
      this.show = false;
    }
    this.arr.splice(index, 1);
    console.log(this.form.spec_item)
    this.creatTable();
  }
  changeVal(index) {
    this.arr[index] = this.specItems[index].standardValue;
  }
  setParentInput(val, index) {
      this.arr[index] = val;
      let  newSpecItem = {};
      for (let item in this.specItems) {
          newSpecItem[this.specItems[item].standardValue] = this.specItems[item].specNames;
      }
      if (newSpecItem) {
          this.form.spec_item = newSpecItem;
      }
  }
  addSpecVal(index) {
    for (let i = 0; i < this.specItems.length - 1; i++) {
      // if (this.specItems[index].standardValue === this.specItems[i].standardValue) {
      //   console.log(this.specItems[index])
      //   console.log(this.specItems[i])
      //   this.specItems[index].standardValue = '';
      //   this.specItems[index].specName = '';
      //   return;
      // }
    }
    if (!this.specItems[index].specName || !this.specItems[index].standardValue) return;
    this.$set(this.specItems[index], 'isTrigger', true);
    // 判断重复添加
    for (let i = 0; i < this.specItems[index].specNames.length; i++) {
      if (this.specItems[index].specName === this.specItems[index].specNames[i]) {
        return;
      }
    }
    this.specItems[index].specNames.push(this.specItems[index].specName);
    this.show = true;
    this.disable = true;
    // 请求添加规格接口并组装规格参数
    this.searchItem.item=this.specItems[index].standardValue
    this.searchItem.parent_id='0'
    goodsApi.saveItem(this.searchItem)
    .then((res: any) => {
      let a={id:"",item:"",parent_id:"",children:[]}
          a.id=res.data.data.id
          a.item=res.data.data.item
          a.parent_id=res.data.data.parent_id
      if(this.addSpec.length>0){
        this.addSpec.forEach(item=>{
          if(item.item!=res.data.data.item){
            this.addSpec.push(a)
          }
        })
      }else{
        this.addSpec.push(a)
      }
      this.searchItem.item=this.specItems[index].specName
      this.specItems[index].specName = '';
      goodsApi.saveItem(this.searchItem)
      .then((res: any) => {
        let b={id:"",item:"",parent_id:a.id,children:[]}
            b.id=res.data.data.id
            b.item=res.data.data.item
        this.addSpec[index].children.push(b) 
        let arr:any=[]
        this.addSpec.forEach(item=>{
          if(item.children.length>0){
            arr.push(item)
          }
        })
        this.form.spec_item=arr
        console.log(this.form.spec_item)
        this.creatTable();
        
      });
    });
  }
  creatTable() {
    this.result = [];
    let _arr:any = [];
    let zzz = [];
    let _item:any = [];
    if (this.specItems.length) {
      for (let i = 0; i < this.specItems.length; i++) {
        let thTitle = this.specItems[i].standardValue;
        _arr.push(thTitle);
      }
      for (let i = 0; i < _arr.length; i++) {
        if (this.arr.indexOf(_arr[i]) === -1) {
          this.arr.push(_arr[i]);
        }
      }
      // 二维数组
      this.allSpec = this.specItems.map((item) => {
        return item.specNames;
      });
      this.trs = this.doExchange(this.allSpec);
      let _trs:any = []
      this.trs.map(item => {
        _trs.push(item.split(','));
      });
      this.trs = _trs;
      let _trsVals:any = [];
      // for (let i = 0; i < this.trs.length; i++) {
      // }
      this.trs.forEach((item:any,i:any)=>{
        _trsVals.push({
          key:"",
          key_name:"",
          bar_code:"",//	条形码
          sku:"",//sku
          status:"",//状态
          price:"",//	规格售价
          original_price:0,//	原价
          suggest_price:"",//	建议售价
          channel_settle_price:"",//	渠道商结算价
          sell_price:"",//商家结算价
          platform_price:"",//供应商结算价
          vendor_price:"",//供应价
          stock: 0,//	库存
          spec_img:"",
          sale_stock:"",
          channelPrice:"",//渠道结算价
          supplierPrice:""//商家结算价
        });
        const _arr = this.trs[i];
        console.log(this.arr)
        console.log(this.trs[i])
        let key_name;
        this.arr.forEach(items=>{
          this.trs.forEach(item=>{
            key_name+=items+':'+item+'_'
          })
        })
        // console.log(key_name)
        // console.log(this.arr[i])
        this.trsVals = _trsVals;
        for (let i = 0; i < _arr.length; i++) {
          let obj = {
            label: this.trs[i],
            isActive: true
          };
          this.switchArr.push(obj);
        }
        let _obj = {
          // item: _arr,
          key:this.trsVals[i].key,
          key_name:this.trsVals[i].key_name,
          bar_code:this.trsVals[i].bar_code,//	条形码
          sku:this.trsVals[i].sku,//sku
          status:this.trsVals[i].status,//状态
          price:this.trsVals[i].price,//	规格售价
          original_price:this.trsVals[i].original_price,//	原价
          suggest_price:this.trsVals[i].suggest_price,//	建议售价
          channel_settle_price:this.trsVals[i].channel_settle_price,//	渠道商结算价
          sell_price:this.trsVals[i].sell_price,//商家结算价
          platform_price:this.trsVals[i].platform_price,//供应商结算价
          vendor_price:this.trsVals[i].vendor_price,//供应价
          stock: this.trsVals[i].stock,//	库存
          spec_img:this.trsVals[i].spec_img,
          sale_stock:this.trsVals[i].sale_stock,
          channelPrice:this.trsVals[i].channelPrice,//渠道结算价
          supplierPrice:this.trsVals[i].supplierPrice//商家结算价
        };
        this.result.push(_obj);
        this.form.spec_goods_price = this.result;
      })
    }
  }
  // 混合数据
  doExchange(doubleArrays) {
    let len = doubleArrays.length;
    if (len >= 2) {
      let arr1 = doubleArrays[0];
      let arr2 = doubleArrays[1];
      let len1 = doubleArrays[0].length;
      let len2 = doubleArrays[1].length;
      let newlen = len1 * len2;
      let temp = new Array(newlen);
      let index = 0;
      for (let i = 0; i < len1; i++) {
        for (let j = 0; j < len2; j++) {
          temp[index] = arr1[i] + ',' + arr2[j];
          index++;
        }
      }
      let newArray = new Array(len - 1);
      newArray[0] = temp;
      if (len > 2) {
        let _count = 1;
        for (let i = 2; i < len; i++) {
          newArray[_count] = doubleArrays[i];
          _count++;
        }
      }
      return this.doExchange(newArray);
    } else {
      return doubleArrays[0];
    }
  }
  // 规格开关
  switchChange(event, index) {
    if (!event) {
      this.result.splice(index, 1);
    } else {
      let _obj = {
        // item: this.trs[index],
        // price: this.trsVals[index].price,
          // // original_price:this.trsVals[i].original_price || 0,
          // // bar_code:this.trsVals[i].bar_code || '',
          // // sku:this.trsVals[i].sku || '',
          // // expiration_time:this.trsVals[i].expiration_time || '',
          // // spec_img:this.trsVals[i].spec_img || '',
          // original_price:this.trsVals[index].original_price || 0,
          // bar_code:this.trsVals[index].bar_code || '',
          // sku:this.trsVals[index].sku || '',
          // expiration_time:this.trsVals[index].expiration_time || '',
          // spec_img:this.trsVals[index].spec_img || '',
          key_name:this.trsVals[index].key_name || '',
          bar_code:this.trsVals[index].bar_code || '',//	条形码
          sku:this.trsVals[index].sku || '',//sku
          status:this.trsVals[index].status || '',//状态
          price:this.trsVals[index].price || '',//	规格售价
          original_price:this.trsVals[index].original_price || '',//	原价
          suggest_price:this.trsVals[index].suggest_price || '',//	建议售价
          channel_settle_price:this.trsVals[index].channel_settle_price || '',//	渠道商结算价
          sell_price:this.trsVals[index].sell_price || '',//商家结算价
          platform_price:this.trsVals[index].platform_price || '',//供应商结算价
          vendor_price:this.trsVals[index].vendor_price || '',//供应价
          stock: this.trsVals[index].stock || '',//	库存
          spec_img:this.trsVals[index].spec_img || '',
          sale_stock:this.trsVals[index].sale_stock || '',
          channelPrice:this.trsVals[index].channelPrice || '',//渠道结算价
          supplierPrice:this.trsVals[index].supplierPrice || ''//商家结算价
      };
      this.result.splice(index, 0, _obj);
      this.form.spec_goods_price = this.result;
    }
  }
  // 一级分类
  handleChange(value:any) {
    this.kindList.forEach((item:any)=>{
      if(item.id==value){
        this.kindListTwo=item.children
      }
    })
  }
  // 二级分类
  handleChangeTwo(value){
    this.kindListTwo.forEach((item:any)=>{
      if(item.id==value){
        this.kindListThree=item.children
      }
    })
  }
  // 上传图片子组件传递过来的图片路径
  propImg(imgPath: any){
    this.form.logo = imgPath;
    console.log(imgPath)
  }
  // 上传多张图片子组件传递过来的图片路径
  propImgList(imgPath: any){
    this.form.images = imgPath;
  }
  // 富文本编辑
  editorChange(data:any) {
    this.form.content = data.content;
  }
  // 取消
  cancel(){
    this.$router.push({
      path:'/goodsList'
    })
  }
  // 新建广告商
  handleAdd(){
    let a={id:'' ,code:'',weight:this.form.advertisers.length+1}
    this.form.advertisers.push(a)
    console.log(this.form)
  }
  // 提交
  submitFormAdd(formName: any) {
    (this.$refs[formName] as any).validate((valid: boolean) => {
      if (valid) {
          
        if(this.dateTime==null){
          this.dateTime=["",""]
        }
        if(this.saleDateTime==null){
          this.saleDateTime=["",""]
        }
        this.form.verify_start_time=this.dateTime[0];
        this.form.verify_end_time=this.dateTime[1];
        this.form.sale_on_time=this.saleDateTime[0];
        this.form.sale_off_time=this.saleDateTime[1];
      }
      console.log(this.form)
      // goodsApi.saveGoods(this.form)
      // .then((res: any) => {
      //   if(res.data.status){
      //     this.$message({
      //       message: '操作成功',
      //       type: "success"
      //     });
      //   }
        // this.$router.push({
        //   path:'/goodsList'
        // })
        // this.$emit("loadData")
      // });
    });
  }
  handleAvatarSuccess(res:any, file:any) {
    this.form.imgPath = res.data.fileUrl;
  }
  created() {
   // 标签
    goodsApi.labelList(1,9999999)
      .then((res: any) => {
        this.labelList = res.data.data.data;
    });
    // 商家
    businessApi.businessList(1,999999,this.searchMapB)
      .then((res: any) => {
        this.businessList = res.data.data.list;
    });
    // 供应商
     supplierApi.supplierList(1,999999,this.searchMapS)
      .then((res: any) => {
        this.supplierList = res.data.data.lists.data;
    });
    // 分类
    goodsApi.goodsKind()
      .then((res: any) => {
        this.kindList = res.data.data;
    });
   }
}
</script>

<style lang="scss" scoped>
.dialog-footer{
  padding-left: 50px
}
.spec-box{
  border: 1px solid #d8d8d8;
  min-height: 200px;
  max-height: 800px;
  overflow-y: scroll;
  padding: 10px;
  .el-input,
  .el-select {
    margin-right: 10px;
    margin-bottom: 10px;
  }
}
.form-box {
  margin-bottom: 20px;
  .el-input,
  .el-select {
    width: 200px !important;
  }
  .title{
    line-height: 60px;
    font-weight: bold;
    font-size: 16px;
  }
  .price-title{
    font-size: 14px;
    font-weight: bold;
    margin-bottom: 20px;
  }
  .price-txt{
    font-size: 14px;
    color: #333;
  }
  .price-tip{
    color: red;
    font-size: 12px;
    margin-left: 50px;
  }
  // .spec-table{
  //   text-align: center;
  //   border: 1px solid #eee;
  //   .el-input{
  //     width: 100px !important;
  //     margin: 10px 0;
  //   }
  //   th{
  //     line-height: 50px;
  //     height: 50px;
  //   }
  //   thead{
  //     background: #f5f5f5;
  //   }
  //   th,td{
  //     border: 1px solid #eee;
  //   }
  // }
  .specBox {
    width: 75%;
    min-height: 200px;
    max-height: 800px;
    overflow-y: scroll;
    padding: 10px;
    border: 1px solid #d8d8d8;
    .specTable {
      border: 1px solid #e3e3e3;
      thead {
        background: #f5f5f5;
      }
      th,td {
        width: 120px;
        padding: 3px 8px;
        text-align: center;
        border: 1px solid #e3e3e3;
        .el-input{
          width: 100px !important;
        }
      }
    }
  }
}
</style>
